/**
 * 搜索历史管理
 * */ 
class SearchKeyManager {
	
	constructor(storageKey, max) {
		this.storageKey = storageKey;
		let storage = uni.getStorageSync(storageKey);
		this.searchKeyList = storage.length ? storage : [];
		this.MAX = max;
	}
	
	/**
	 * 添加搜索记录，若有记录，就删除记录中的item，
	 * */ 
	addKey(key) {
		let searchKeyList = this.searchKeyList;
		let index = this.indexOf(key);
		if (index > -1) {
			searchKeyList.splice(index, 1);
		}
		searchKeyList.unshift(key);
		if (searchKeyList.length > this.MAX)
			searchKeyList.pop();
		this.syncLocalStorage();
	}
	
	/**
	 * 删除搜索记录
	 * */ 
	removeKey(key) {
		let index = this.indexOf(key);
		this.searchKeyList.splice(index, 1);
		this.syncLocalStorage();
	}
	
	/**
	 * 清除搜索记录
	 * */ 
	clearKey() {
		this.searchKeyList = [];
		uni.clearStorageSync(this.storageKey);
	}
	
	/**
	 * 同步localstorage
	 * */ 
	syncLocalStorage() {
		uni.setStorageSync(this.storageKey, this.searchKeyList);
	}
	
	indexOf(key) {
		return this.searchKeyList.indexOf(key);
	}
}

export default SearchKeyManager;